package com.yape.webCrawler.impl;

import com.yape.annotation.CrawlerLog;
import com.yape.po.NewStockListing;
import com.yape.webCrawler.base.BaseCrawler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Calendar;

/**
 * @Author Hazuki
 * @Date 2025/5/23 上午10:01
 * @Version 1.0
 */
@Component("newStock")
public class NewStockListingCrawler extends BaseCrawler {
    private static final String API_URL = "https://vip.stock.finance.sina.com.cn/corp/go.php/vRPD_NewStockIssue/page/1.phtml";
    private static final Logger log = LoggerFactory.getLogger(NewStockListingCrawler.class);


//    /**
//     * 设置最大爬取数量
//     * @param maxStocks 最大爬取数量
//     */
//    public void setMaxStocks(int maxStocks) {
//        this.maxStocks = maxStocks > 0 ? maxStocks : Integer.MAX_VALUE;
//    }

    @Override
    @CrawlerLog
    public List<NewStockListing> execute() throws IOException {
        Document doc = Jsoup.connect(getApiUrl()).get();
        Element newStockTable = doc.getElementById("con02-0").getElementById("NewStockTable");
        Elements rows = newStockTable.select("tbody > tr");

        List<NewStockListing> newStockList = new ArrayList<>();

        log.info("============爬虫数据表============");
        log.info(String.format("%-15s | %-15s", "股票名称", "上市日期"));
        log.info("--------------------------------");

        int count = 0;
        long now = System.currentTimeMillis();
        long oneWeekMillis = 7L * 24 * 60 * 60 * 1000;
        for (Element row : rows) {
            if (row.children().size() < 5) {
                continue;
            }

            try {
                String stockName = row.select("td:nth-child(3) a").text();
                String listingDate = row.select("td:nth-child(4) div").text().trim();

                // Skip header rows or invalid data
                if ("证券简称".equals(stockName) ||
                        "上市日期".equals(listingDate) ||
                        stockName.isEmpty() ||
                        listingDate.isEmpty() ||
                        !listingDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
                    continue;
                }

                long listingTimestamp = new SimpleDateFormat("yyyy-MM-dd").parse(listingDate).getTime();
                // 只保留最近一周上市的证券
                if (now - listingTimestamp > oneWeekMillis) {
                    continue;
                }
                newStockList.add(new NewStockListing(
                        null,
                        stockName,
                        listingDate,
                        new java.util.Date(),
                        new java.util.Date()
                ));
                log.info(String.format("%-15s | %-15s", stockName, listingDate));
                count++;

                // 达到最大爬取数量时终止循环
                int maxStocks = Integer.MAX_VALUE;
                if (count >= maxStocks) {
                    log.info("达到最大爬取数量: {}", maxStocks);
                    break;
                }
            } catch (Exception e) {
                log.error("解析数据时出错: {}", e.getMessage());
            }
        }

        return newStockList;
    }

    @Override
    protected String getApiUrl() {
        return API_URL;
    }
}